<?php 

class CategoryController extends VerifyController{
	public $model;
	
	public function __init(){
	    $this->model = K('category');
	}
	public function index(){
		$data = M()->join("__category__ c join __type__ t on c.typeid=t.tid")->all();
		//调用模型的getData获得组合好的数组
		$data = Data::tree($data, 'cname','cid','pid');
		$this->assign("data",$data);
	    $this->display();
	}
	public function add(){
		if(IS_POST){
			if(!$this->model->addData()){
				$this->error($this->model->error);
			}
			$this->success("添加分类成功");
		}
		//获取分类传递到前台
		$category = $this->model->all();
		$category = Data::tree($category, 'cname','cid','pid');
		$this->assign("category",$category);
		//获取类型传递到前台
		$type = K('type')->all();
		$this->assign("type",$type);
	    $this->display();
	}
	//删除分类
	public function del(){
	    $cid = Q("get.cid");		
		if(!$this->model->delData($cid)){
			$this->error($this->model->error);
		}
		$this->success("删除分类成功",U('index'));
	}
	//删除全部包括子分类
	public function delall(){
	    $cid = Q("get.cid");		
		if(!$this->model->delallData($cid)){
			$this->error($this->model->error);
		}
		$this->success("删除分类成功",U('index'));
	}
	//编辑分类
	public function edit(){
		$cid = Q('get.cid',0,'intval');
		if(IS_POST){
			if(!$this->model->upData($cid)){
				$this->error($this->model->error);
			}
			$this->success("修改成功",U("index"));
		}
		//获取分类传递到前台
		$category = $this->model->all();
		$category = Data::tree($category, 'cname','cid','pid');
		$cidSonarr = $this->model->getSon($category,$cid);
		$cidSonarr[] = $cid;
		foreach ($category as $k => $v) {
			if(in_array($v['cid'], $cidSonarr)){
				unset($category[$k]);
			}
		}
		$this->assign("category",$category);
		//获取类型传递到前台
		$type = K('type')->all();
		$this->assign("type",$type);
		//获取自己cid的分类信息传递到前台
		$data = $this->model->where("cid=$cid")->find();
		$this->assign("data",$data);
		$this->display();
	}
	public function ajaxText(){
	    $cid = Q('post.cid',0,'intval');
		$data = $this->model->all();
		$sonCid = $this->model->getSon($data,$cid);
		$this->ajax($sonCid);
	}
	public function uploadpic(){
	     $upload = new Upload('Upload/Category/' . date('y/m'));
		 $file = $upload->upload();
		 if (empty($file)) {
		 	$this->ajax('上传失败');
		 } else {
		 	//来这个地方可以缩略图处理
			
		 	$data = $file[0];
			$this->ajax($data);
		 }
	}
	public function picopen(){
		if(!IS_AJAX) $this->error("非法进入");
	    $cid = Q('cid',0,'intval');
		$data = $this->model->where("cid=$cid")->find();
		if($data){
			if($data['pid'] == 0){
				$this->ajax(1);
			}
		}
		$this->ajax(0);
	}
}
